package com.LostAndFound.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.LostAndFound.domain.Category;
import com.LostAndFound.service.CategoryListService;
import com.google.gson.Gson;

public class CategoryListServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	CategoryListService service = new CategoryListService();

	// 获取categoryList，返回给Ajax
	public void findAllCategoryToAjax(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Category> categoryList = null;
		categoryList = service.showAllCategoryName();
		Gson gson = new Gson();
		String json = gson.toJson(categoryList);
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write(json);
	}
	
	// =========================
	
	// 分页，展示记录
	public void getCategoryListForEasyUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 当前页
		int pageNumber = Integer.parseInt(request.getParameter("page"));
		// 每页总条数
		int pageSize = Integer.parseInt(request.getParameter("rows"));
		// 记录总条数
		int total = service.getTotalCategoryListForEasyUI();
		// 全部记录
		List<Category> categoryList = null;
		categoryList = service.getCategoryListForEasyUI(pageNumber,pageSize);
		Gson gson = new Gson();
		String rows = gson.toJson(categoryList);
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("{\"total\":"+total+",\"rows\":"+rows+"}");
	}
	// 删除分类
	public void handleDeleteCategoryForEasyUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String cid = request.getParameter("cid");
		boolean success = service.handleDeleteCategoryForEasyUI(cid);
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("{\"success\":"+success+"}");
	}
	// 编辑分类
	public void handleEditCategoryEasyUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer cid = Integer.parseInt(request.getParameter("cid"));
		String cname = request.getParameter("cname");
		Category category = new Category();
		category.setCid(cid);
		category.setCname(cname);
		boolean success = service.handleEditCategoryEasyUI(category);
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("{\"success\":"+success+"}");
	}
	// 添加分类
	public void handleAddCategoryEasyUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String cname = request.getParameter("cname");
		Category category = new Category();
		category.setCname(cname);
		boolean success = service.handleAddCategoryEasyUI(category);
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("{\"success\":"+success+"}");
	}
	
}